import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;


class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;

    TreeNode() {
    }

    TreeNode(int val) {
        this.val = val;
    }

    TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}

class Solution01 {
    // 利用层序遍历统计每一层的最大值
    public List<Integer> largestValues(TreeNode root) {
        List<Integer> ret = new ArrayList<Integer>();
        if (root == null) {
            return ret;
        }
        Queue<TreeNode> q = new LinkedList<TreeNode>();
        // 根节点入队
        q.offer(root);
        while (!q.isEmpty()) {
            int n = q.size();
            // 定义一个变量记录每层的最大值
            int tmp = Integer.MIN_VALUE;
            for (int i = 0; i < n; i++) {
                TreeNode node = q.poll();
                tmp = Math.max(tmp, node.val);
                if (node.left != null) {
                    q.offer(node.left);
                }
                if (node.right != null) {
                    q.offer(node.right);
                }
            }
            ret.add(tmp);
        }
        return ret;
    }
}